//
//  DZZMapViewController.m
//  DZZTravel
//
//  Created by xalo on 16/7/19.
//  Copyright © 2016年 Eason. All rights reserved.
//

#import "DZZMapViewController.h"
#import <mapkit/MapKit.h>//地图框架
@interface DZZMapViewController ()<MKMapViewDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong)MKMapView *mapView;
//天气的数组
@property (nonatomic,strong)NSMutableArray *weatherArray;

//位置管理者
@property (nonatomic,strong)CLLocationManager *collocationManager;

@property (nonatomic,strong)DZZLoanimation *animation;
//现在的地址
@property (nonatomic,strong)NSString *nowAdress;
//要去的地址
@property (nonatomic,strong)NSString *willAdress;

@property (nonatomic,strong)UITableView *tableView;


@property (nonatomic,strong)NSString *cityName;



@end

@implementation DZZMapViewController

- (NSMutableArray *)weatherArray{
    if (!_weatherArray) {
        _weatherArray = [NSMutableArray array];
    }
    return _weatherArray;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.mapView.height, self.view.width, self.view.height-self.mapView.height) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}

- (MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc]initWithFrame:CGRectMake(0, 64, self.view.width, self.view.height-130-45-120-40-70)];
    }
    return _mapView;
}
- (CLLocationManager *)collocationManager{
    
    if (!_collocationManager) {
        _collocationManager = [[CLLocationManager alloc]init];
    }
    return _collocationManager;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.collocationManager requestWhenInUseAuthorization];
    
    self.willAdress = self.naviModel.address;
}



- (void)viewDidLoad {
    [super viewDidLoad];

//    设置tableView
    [self setManyTableView];
//    加载天气状况
    [self loadWeatherData];
    
    
/*
 {
 "status": 0,
 "result": {
 "location": {
 "lng": 108.90695699999995,
 "lat": 34.229657035149174
 },
 "formatted_address": "陕西省西安市雁塔区高新路",
 "business": "科技二路,高新路,科技一路",
 "addressComponent": {
 "adcode": "610113",
 "city": "西安市",
 "country": "中国",
 "direction": "",
 "distance": "",
 "district": "雁塔区",
 "province": "陕西省",
 "street": "高新路",
 "street_number": "",
 "country_code": 0
 },
 "pois": [],
 "poiRegions": [
 {
 "direction_desc": "内",
 "name": "高新水晶城",
 "tag": "房地产"
 }
 ],
 "sematic_description": "高新水晶城内,高新·水晶城-B2栋西北51米",
 "cityCode": 233
 }
 }
 */
//    
//    [RequestManager fectDataWithUrl:@"http://api.map.baidu.com/geocoder/v2/?output=json&location=34.229657,108.906957&ak=5m8ce8u7yxtruSZoFlHDB8Ny" parameter:@{} method:@"GET" compelet:^(NSData *data) {
//        
//        
//        
//        
//    } upDateUI:^{
//        
//    }];
//    
    
#pragma mark-------- 设置地图----------
    
//    允许用户访问
    [self.collocationManager requestWhenInUseAuthorization];
    [self.collocationManager startUpdatingLocation];
    
    NSLog(@"+++++++++++++++++++++++++++++%@",self.naviModel.address);
    NSLog(@"++++++++++++++++++++++++++%@",self.naviModel.appMainTitle);

//    传过来的经纬度
    NSNumber *lati = self.naviModel.latitude;
    NSNumber *lng = self.naviModel.longitude;
    
    CLLocationDegrees latitude = [lati doubleValue];
    CLLocationDegrees longtitude = [lng doubleValue];
    CLLocationCoordinate2D coordination = CLLocationCoordinate2DMake(latitude, longtitude);
    
    
//    设置大头针
    self.animation = [[DZZLoanimation alloc]init];
    self.animation.title = self.naviModel.appMainTitle;
    self.animation.subtitle = self.naviModel.address;
    
    self.animation.coordinate = coordination;
    
    
    [self.mapView setRegion:MKCoordinateRegionMakeWithDistance(coordination, 7000, 7000) animated:YES];
    
    self.mapView.showsUserLocation = YES;
    
//    跟踪模式
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
//    不能旋转
    self.mapView.rotateEnabled = NO;
    
//添加视图
    [self.view addSubview:self.mapView];
    
    self.mapView.delegate = self;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"导航" style:UIBarButtonItemStylePlain target:self action:@selector(naviAction)];
    
    
}


//    设置tableView
- (void)setManyTableView{
    
    //    注册cell
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DZZWeatherTableViewCell" bundle:nil] forCellReuseIdentifier:@"DZZWeatherTableViewCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DZZWeatherElseTableViewCell" bundle:nil] forCellReuseIdentifier:@"DZZWeatherElseTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DZZAdressTableViewCell" bundle:nil] forCellReuseIdentifier:@"DZZAdressTableViewCell"];
    
    
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = [UIColor whiteColor];
    
}

//加载天气数据
- (void)loadWeatherData{
    
    [RequestManager fectDataWithUrl:@"http://appapi.yaochufa.com/v2/Product/GetWeatherInfoByCity?system=ios&channel=AppStore&lang=app&imei=086DA4DD-1FAB-421A-8AC3-3CF9F2718437&productId=24197&machineCode=086DA4DD-1FAB-421A-8AC3-3CF9F2718437&version=5.2.3&cityName=%E8%A5%BF%E5%AE%89" parameter:@{} method:@"GET" compelet:^(NSData *data) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//        self.cityName = dic[@"data"][@"results"][0][@"currentCity"];
//        
//        for (NSDictionary *dic2 in dic[@"data"][@"results"][0][@"weather_Data"]) {
//            NSLog(@"%@",dic2);
//            DZZNaviWeatherModel *weather = [[DZZNaviWeatherModel alloc]init];
//            [weather setValuesForKeysWithDictionary:dic2];
//            [self.weatherArray addObject:weather];
//        }
        
        
    } upDateUI:^{
        
        
        [self.tableView reloadData];
        
    }];
}
//http://api.map.baidu.com/geocoder/v2/?output=json&location=34.229657,108.906957&ak=5m8ce8u7yxtruSZoFlHDB8Ny
//导航事件
- (void)naviAction{
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder geocodeAddressString:@"西安市科技二路" completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
//             self.mapView.showsUserLocation = YES;
        
//     地理位置信息
        CLPlacemark *markXiAn = placemarks.firstObject;
        [geocoder geocodeAddressString:self.naviModel.address completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            CLPlacemark *markLaSa = placemarks.firstObject;
            
    
            
//            设置导航的地图类型和导航方式
            NSDictionary *dic = @{MKLaunchOptionsMapTypeKey:@(MKMapTypeStandard),MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving};//地图类型
            
            
            MKMapItem *item1 = [[MKMapItem alloc]initWithPlacemark:[[MKPlacemark alloc]initWithPlacemark:markXiAn]];
            
            MKMapItem *item2 = [[MKMapItem alloc]initWithPlacemark:[[MKPlacemark alloc]initWithPlacemark:markLaSa]];
            //            开启导航
            [MKMapItem openMapsWithItems:@[item1,item2] launchOptions:dic];
            
        }];
        
    }];
    
    NSLog(@"%@",self.nowAdress);
    NSLog(@"%@",self.willAdress);
}
//将要开始加载地图
- (void)mapViewWillStartLoadingMap:(MKMapView *)mapView{
    NSLog(@"将要加载地图");
}
//显示区域发生变化
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
    NSLog(@"显示区域发生变化");
}

//地图加载完毕
- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView{
    NSLog(@"地图加载完毕");
//    添加大头针
    [self.mapView addAnnotation:self.animation];
    
}
//用户位置获取
- (void)mapViewDidStopLocatingUser:(MKMapView *)mapView{
    NSLog(@"用户位置获取");
    
    
}


//更新用户位置
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{

    
    //    地理编码
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    //    将经纬度转换成地址
    
    [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *mark = placemarks.firstObject;
//        当前位置信息
        userLocation.title = mark.name;
        
        self.nowAdress = mark.name;
        NSLog(@"-------------------------------®%@",self.nowAdress);
    }];
//
//        
}

//点击大头针
//- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
//    NSLog(@"点击了大头针");
//    
//}
//大头针的样式
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //    如果当前显示的大头针样式不是我们自己定义的，那么返回空值
    if (![annotation isKindOfClass:[DZZLoanimation class]]) {
        return nil;
    }
    //    标识符
    static NSString *identifier = @"annotation";
    //    从重用集合去取大头针视图
    
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    if (!annotationView) {
        //    创建大头针视图
        annotationView = [[MKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:identifier];
    }
    //   设置大头针属性
    annotationView.annotation = annotation;
//    annotationView.image = [UIImage imageNamed:@"1"];
    //    设置显示在气泡左右的图片
//    annotationView.leftCalloutAccessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"1"]];
    
    //    从天而降(只有用系统的才能有反应)
    annotationView.animatesDrop = YES;
    
    //    设置气泡偏移量
    annotationView.calloutOffset = CGPointMake(0, -10);
    //    设置可以显示气泡
    annotationView.canShowCallout = YES;
    
    
    return annotationView;

    
}

#pragma mark ---------------tableViewDelegate--------------------------

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.weatherArray.count+1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
//    if (self.weatherArray.count >0) {
//        cell.textLabel.text = [self.weatherArray[indexPath.row] wind];
//    }
    
    if (indexPath.row == 0) {
        
      DZZAdressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DZZAdressTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if(indexPath.row == 1){
        
        DZZWeatherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DZZWeatherTableViewCell" forIndexPath:indexPath];
        
        cell.cityLabel.text = self.cityName;
        if (self.weatherArray.count >0) {
            
            
            [cell setCellForModel:self.weatherArray[indexPath.row -1]];
        }
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else{
        DZZWeatherElseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DZZWeatherElseTableViewCell" forIndexPath:indexPath];
        if (self.weatherArray.count >0) {
            
        
        [cell setCellWithModel:self.weatherArray[indexPath.row -1]];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 1) {
        return 130;
    }else if (indexPath.row == 0){
        return 45;
    }
    
    else{
        return 40;
    }
}



@end
